import { Image } from 'expo-image';
import { Platform, StyleSheet, TouchableOpacity, Alert, ActivityIndicator, ScrollView } from 'react-native';
import { useState, useEffect } from 'react';

import { HelloWave } from '@/components/HelloWave';
import ParallaxScrollView from '@/components/ParallaxScrollView';
import { ThemedText } from '@/components/ThemedText';
import { ThemedView } from '@/components/ThemedView';
import BluetoothService, { BluetoothDeviceInfo } from '@/services/BluetoothService';

export default function HomeScreen() {
  const [isLoading, setIsLoading] = useState(false);
  const [connectedDevices, setConnectedDevices] = useState<BluetoothDeviceInfo[]>([]);

  const handleShowConnectedDevices = async () => {
    if (isLoading) return;

    setIsLoading(true);
    try {
      const devices = await BluetoothService.getConnectedDevices();
      setConnectedDevices(devices);
      
      if (devices.length === 0) {
        Alert.alert('提示', '当前没有已连接的蓝牙设备');
      } else {
        Alert.alert('获取成功', `找到 ${devices.length} 个已连接的蓝牙设备`);
      }
    } catch (error: any) {
      Alert.alert('获取失败', error.message || '获取蓝牙设备信息时出现错误');
      setConnectedDevices([]);
    } finally {
      setIsLoading(false);
    }
  };

  const renderDevice = (device: BluetoothDeviceInfo) => (
    <ThemedView key={device.id} style={styles.deviceContainer}>
      <ThemedView style={styles.deviceInfo}>
        <ThemedText type="defaultSemiBold">{device.name}</ThemedText>
        <ThemedText style={styles.deviceAddress}>{device.address}</ThemedText>
        <ThemedText style={styles.connected}>已连接</ThemedText>
        {device.rssi && (
          <ThemedText style={styles.deviceRssi}>信号强度: {device.rssi} dBm</ThemedText>
        )}
      </ThemedView>
    </ThemedView>
  );

  return (
    <ParallaxScrollView
      headerBackgroundColor={{ light: '#A1CEDC', dark: '#1D3D47' }}
      headerImage={
        <Image
          source={require('@/assets/images/partial-react-logo.png')}
          style={styles.reactLogo}
        />
      }>
      <ThemedView style={styles.titleContainer}>
        <ThemedText type="title">ESP32 蓝牙控制器</ThemedText>
        <HelloWave />
      </ThemedView>

      {/* 获取已连接设备按钮 */}
      <ThemedView style={styles.stepContainer}>
        <ThemedText type="subtitle">蓝牙设备信息</ThemedText>
        <TouchableOpacity
          style={[styles.getDevicesButton, isLoading && styles.loadingButton]}
          onPress={handleShowConnectedDevices}
          disabled={isLoading}
        >
          {isLoading ? (
            <ActivityIndicator color="#fff" size="small" />
          ) : null}
          <ThemedText style={styles.buttonText}>
            {isLoading ? '获取中...' : '查看蓝牙设备信息'}
          </ThemedText>
        </TouchableOpacity>
      </ThemedView>

      {/* 已连接设备列表 */}
      {connectedDevices.length > 0 && (
        <ThemedView style={styles.stepContainer}>
          <ThemedText type="subtitle">已连接的蓝牙设备</ThemedText>
          {connectedDevices.map(device => renderDevice(device))}
        </ThemedView>
      )}

      {/* 使用说明 */}
      <ThemedView style={styles.stepContainer}>
        <ThemedText type="subtitle">使用说明</ThemedText>
        <ThemedText>
          点击"显示已连接的蓝牙设备"按钮查看蓝牙设备信息
        </ThemedText>
        <ThemedText style={styles.noteText}>
          注意：当前版本显示模拟数据，避免蓝牙库兼容性问题
        </ThemedText>
      </ThemedView>
    </ParallaxScrollView>
  );
}

const styles = StyleSheet.create({
  titleContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 8,
  },
  stepContainer: {
    gap: 8,
    marginBottom: 16,
  },
  reactLogo: {
    height: 178,
    width: 290,
    bottom: 0,
    left: 0,
    position: 'absolute',
  },
  getDevicesButton: {
    backgroundColor: '#007AFF',
    paddingHorizontal: 24,
    paddingVertical: 12,
    borderRadius: 8,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    gap: 8,
    marginTop: 8,
  },
  loadingButton: {
    backgroundColor: '#5AC8FA',
  },
  deviceContainer: {
    paddingVertical: 12,
    paddingHorizontal: 16,
    marginVertical: 4,
    backgroundColor: '#f5f5f5',
    borderRadius: 8,
    elevation: 2,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.2,
    shadowRadius: 2,
  },
  deviceInfo: {
    flex: 1,
  },
  deviceAddress: {
    fontSize: 12,
    color: '#666',
    marginTop: 2,
  },
  deviceRssi: {
    fontSize: 12,
    color: '#888',
    marginTop: 2,
  },
  connected: {
    fontSize: 12,
    marginTop: 2,
    fontWeight: 'bold',
    color: '#28a745',
  },
  buttonText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: 'bold',
  },
  noteText: {
    fontSize: 12,
    color: '#888',
    fontStyle: 'italic',
    marginTop: 4,
  },
});
